package com.ochnas.volunteersignup.ui;

import java.io.IOException;
import java.util.List;
import java.util.SortedMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ochnas.volunteersignup.domain.FilledVolunteerRequisition;
import com.ochnas.volunteersignup.domain.Position;
import com.ochnas.volunteersignup.domain.TimeSlot;
import com.ochnas.volunteersignup.domain.User;
import com.ochnas.volunteersignup.service.EventService;
import com.ochnas.volunteersignup.service.UserService;
import com.ochnas.volunteersignup.service.VolunteerService;


public class GetTimeSlotService extends HttpServlet {
    WebApplicationContext spring;
    private static final long serialVersionUID = -2560989072138239258L;

    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        spring = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EventService eventService = (EventService) spring.getBean("eventService");
        VolunteerService volunteerService = (VolunteerService) spring.getBean("volunteerService");
        UserService userService = (UserService) spring.getBean("userService");
        
        // No id specified - return a list of all positions
        if (request.getRequestURI().endsWith("/") || request.getRequestURI().endsWith("timeslot")) {
            Document doc = DocumentFactory.getInstance().createDocument();
            Element root = doc.addElement("timeslots");
            List<TimeSlot> timeslots = eventService.findAllTimeSlots();
            for (TimeSlot timeSlot : timeslots) {
                root.addElement("timeslot").addAttribute("ref", request.getRequestURL()+"/"+timeSlot.getId());
            }

            response.getOutputStream().println(doc.asXML());
        }

        // If an id was specified, look up that item
        else {
            String id = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
            TimeSlot timeSlot = eventService.findTimeSlot(Long.parseLong(id));
            List<FilledVolunteerRequisition> volunteers = volunteerService.findVolunteersForTimeSlot(timeSlot.getId());
            
            Document xmlResponse = DocumentFactory.getInstance().createDocument();

           	Element timeSlotElement = xmlResponse.addElement("timeslot")
            		.addAttribute("id", String.valueOf(timeSlot.getId()));
        	Element tsPosition = timeSlotElement.addElement("position")
        			.addAttribute("id", String.valueOf(timeSlot.getPosition().getId()));
        		Element startTime = timeSlotElement.addElement("time")
        			.addAttribute("name", "startTime");
        		startTime.addElement("hourOfDay")
        			.addText(String.valueOf(timeSlot.getStartTime().getHourOfDay()));
        		startTime.addElement("minutes")
        			.addText(String.valueOf(timeSlot.getStartTime().getMinutes()));
        		
        		Element endTime = timeSlotElement.addElement("time")
        			.addAttribute("name", "endTime");
        		endTime.addElement("hourOfDay")
        			.addText(String.valueOf(timeSlot.getEndTime().getHourOfDay()));
        		endTime.addElement("minutes")
        			.addText(String.valueOf(timeSlot.getEndTime().getMinutes()));
        		
        			for (FilledVolunteerRequisition v: volunteers) {
						User u = userService.findUserAccount(v.getUser().getId());
		            		
						Element userElement = timeSlotElement.addElement("user")
								.addAttribute("role", "volunteer")
								.addAttribute("id", String.valueOf(u.getId()));

						Element emailElement = userElement
								.addElement("emailAddress");
						emailElement.addText(String
								.valueOf(u.getEmailAddress()));

						Element fNameElement = userElement
								.addElement("firstName");
						fNameElement.addText(String.valueOf(u.getFirstName()));

						Element lNameElement = userElement
								.addElement("lastName");
						lNameElement.addText(String.valueOf(u.getLastName()));

						Element phoneElement = userElement
								.addElement("contactPhoneNumber");
						phoneElement.addText(String.valueOf(u
								.getContactPhoneNumber()));
        			
	        		}
	            
            response.setContentType("text/xml");
            response.getOutputStream().println(xmlResponse.asXML());
        }
    }
}
